import React from "react";
import { Button,Card,Col,Divider,Form,Icon,Input,notification,Row,Tag,Modal,message,Upload,Radio,Spin } from "antd";
import { loadBanner,deleteBanner,setBanner } from "@/services/systemCenter";
import Loading from "@/components/Loading";
import { formatMessage } from "umi-plugin-react/locale";
import request from "@/utils/request";
import { getToken } from '@/utils/token';
import { indexOf, method } from "lodash";
let id = 0;

class BannerManageForm extends React.Component {
  constructor(props) {
    super(props);
    const { id = 0 } = this.props.match.params;
    this.state = {
      loading: false, // 用户详细信息的加载状态，用户页面loading效果
      submiting: false, // 表单提交状态
      detail: {}, // 
      visible: false,
      tagvisible:true,
      previewVisible: false,
      del_id:0,
      id // 
    };
    
  }

  async componentDidMount() {
    this.setState({ loading: true });
    this.loadData();
  }


  // 加载用户信息
  loadData =() => {
    
    loadBanner(id)
      .then(res => {
        this.setState({
          banner:res,
          previewImage: '',
          previewTitle: '',
          previewPath:'',
          sort:0

        })
        let fileList = [];
        res && res.map((e,index) => {

          fileList.push({
            uid: e.id,
            name: 'image.png',
            status: 'done',
            url: e.picture_src,
            path:e.path,
            sort:e.sort
          }) 
        });

        this.setState({fileList:fileList})
      })
      .finally(() => {
        this.setState({
          id:0,
          loading: false
        });
      });
  };

  handleSubmit = async e => {
    e.preventDefault();
    if (this.submiting) {
      return;
    }
    // setState为异步动作，直接设置submiting变量作为限制
    this.submiting = true;
    this.setState({
      submiting: true
    });
    this.props.form.validateFields(async (err, fieldsValue) => {
      if (err) {
        this.submiting = false;
        this.setState({
          submiting: false
        });
        return;
      }

      const params = {
        path: fieldsValue.path,
        sort: fieldsValue.sort,
        id:this.state.id
      };
      // eslint-disable-next-line @typescript-eslint/no-unused-vars
      setBanner(params).then(res => {
        this.submiting = false;
        this.setState({
          submiting: false
        });
        if (res && res.status !== 200) {
        } else {
          notification.success({
            message: "更新成功"
          });
          this.setState({previewVisible: false})
          this.loadData()
          // this.props.history.goBack();
        }
      });
    });
  };

  

  

  handleCancel = () => this.setState({ previewVisible: false });

  getBase64(file) {
    return new Promise((resolve, reject) => {
      const reader = new FileReader();
      reader.readAsDataURL(file);
      reader.onload = () => resolve(reader.result);
      reader.onerror = error => reject(error);
    });
  }

  handlePreview = async file => {
    if (!file.url && !file.preview) {
      file.preview = await this.getBase64(file.originFileObj);
    }

    this.setState({
      id:file.uid,
      sort:file.sort,
      previewImage: file.url || file.preview, 
      previewPath:file.path,
      previewVisible: true,
      previewTitle: file.name || file.url.substring(file.url.lastIndexOf('/') + 1),
    });
  };

  handleChange = ({ fileList }) => {

    // this.setState({ fileList:fileList });
    const hide = message.loading('loading', 0);
    setTimeout(hide, 1000);
    setTimeout(() => {
      this.loadData();
    }, 1000);
    
  }

  
  onRemove = e =>{
    console.log(e)
    this.showDelModal(e.uid)
    return false
  }

  showDelModal(id){
    this.setState({
      del_id:id,
      visible:true
    })
  }

  // 删除
  handleOk = e => {
    this.setState({
      visible: false,
    });
    const id = this.state.del_id

    deleteBanner(id).then(res => {
      this.loadData();
      message.success('删除成功');
    });

  };

  handleDelCancel = e => {
    this.setState({
      visible: false,
      del_id:0
    });
  };

  render() {
    // 686*264
    // 480*252
    const { getFieldDecorator,getFieldValue  } = this.props.form;
    const { submiting } = this.state;
    let token = getToken();
    const headers = {
      Authorization: `${token.token_type} ${token.access_token}`,
      injectHeader: 'true',
    }

    const titleExtraButton = (
      <Row type="flex" gutter={12} align="middle">
        <Col>
          <Button onClick={this.props.history.goBack}>返回</Button>
        </Col>
      </Row>
    );
    const {loading, previewVisible, previewImage,previewPath, fileList, previewTitle,sort } = this.state;
    const rowGutter = [16, 16];

    const uploadButton = (
      <div>
        <Icon type='plus' style={{width:180,lineHeight:'100px'}} />
        
      </div>
    );

    const antIcon = (<Icon type="loading" style={{ fontSize: 24 }} spin />);

    return (
      <Card title="设置首页banner图" extra={titleExtraButton}>
        {loading ? (
          <Loading />
        ) : (
          <Col>
          <p>建议尺寸：1920px*403px,支持jpg、png格式，图片大小不得大于2M</p>
          <div class="bannerUpload">
            <Upload
              name='banner'
              action="/api/admin/bannerAdd"
              headers = {headers}
              listType="picture-card"
              fileList={fileList}
              onPreview={this.handlePreview}
              onChange={this.handleChange}
              onRemove={(e) => this.onRemove(e)}
            >
              {uploadButton}
            </Upload>
          </div>
          <Modal
            visible={previewVisible}
            title= '设置跳转路径'
            footer={null}
            onCancel={this.handleCancel}
          >
            <img alt="example" style={{ width: '100%',marginBottom:'20px' }} src={previewImage} />
            <Form labelCol={{ span: 4 }}  wrapperCol={{ span: 18 }} layout="horizontal">

              <Form.Item label="跳转链接" extra="请填写完整链接，例：http://www.xxx.com">
                {getFieldDecorator("path", {
                  initialValue: previewPath,
                })(<Input style={{width: '100%' }} />)}
              </Form.Item>

              <Form.Item label="排序" extra="排序越大越靠前">
                {getFieldDecorator("sort", {
                  initialValue: sort,
                })(<Input style={{width: '100%' }} />)}
              </Form.Item>
              
              <Button
                type="primary"
                loading={submiting}
                onClick={this.handleSubmit}
                style={{marginLeft:'70%'}}
              >
                确定
              </Button>

            </Form>
          </Modal>

          <Modal
            title="温馨提示"
            visible={this.state.visible}
            onOk={this.handleOk}
            onCancel={this.handleDelCancel}
          >
            <p>数据删除后不可恢复，您确定要删除此条数据吗？</p>
          </Modal>
          </Col>
        )}

        
      </Card>
    );
  }
}

const WrappedBannerManageForm = Form.create({ name: "banner_manage" })(
  BannerManageForm
);
export default WrappedBannerManageForm;
